package com.edu.zql;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by User on 2017/10/13.
 */
public class DeadLock {


    public static void main(String[] args) {

        DeadLock deadLock = new DeadLock();

        Thread thread = deadLock.new ThreadDemo(1);
        Thread thread0 = deadLock.new ThreadDemo(0);



        thread.start();
        thread0.start();


    }


    Lock lock1 = new ReentrantLock();
    Lock lock2 = new ReentrantLock();
    class ThreadDemo extends Thread {

        int flag = 0;

        public ThreadDemo(int flag) {
            this.flag = flag;
        }

        @Override
        public void run() {
            for (;;)
            if (flag == 1) {

                System.out.println("waiting unlock lock1");
                lock1.lock();
                System.out.println("lock lock1");

                System.out.println("do something during lock1 ......");

                System.out.println("waiting unlock lock2");
                lock2.lock();
                System.out.println("lock lock2");

                System.out.println("do something during lock2 ......");

                lock2.unlock();
                System.out.println("unlock lock2");


                lock1.unlock();
                System.out.println("unlock lock1");

            } else {

                System.out.println("waiting unlock lock2");
                lock2.lock();
                System.out.println("lock lock2");

                System.out.println("do something during lock2 ......");

                System.out.println("waiting unlock lock1");
                lock1.lock();
                System.out.println("lock lock1");

                System.out.println("do something during lock1 ......");

                lock1.unlock();
                System.out.println("unlock lock1");

                lock2.unlock();
                System.out.println("unlock lock2");

            }





        }
    }








}
